//前台 index
const HttpException = require('../../exception/http.exception')
const { sign, decode } = require('../../utils/jwt')

const authMiddleware = async (req, res, next) => {
console.log('------authMiddleware-------');
    //00 生成token
    // const jwtToken = await sign('cl@qq.com', 'cl')
    // console.log(jwtToken)

    //01 获取jwt
    //1) header获取 authorization=token
    const authHeader = req.headers.authorization
    console.log("authHeader",authHeader);
    if (!authHeader) {
        return next(new HttpException(401, 'authorization 必须提供1', 'authorization missing'))
    }
    //2)验证authorization格式
    const authHeaderArray = authHeader.split(' ')
    if (authHeaderArray[0] !== 'Token') {
        return next(new HttpException(401, 'authorization 必须提供2', 'authorization missing'))
    }
    //3)获取jwt token; jwt token存在校验
    const token = authHeaderArray[1]// 00生成的token 通过authHeader.split(' ')拆分后=>authHeaderArray[1]
    if (!token) {
        return next(new HttpException(401, 'authorization 必须提供3', 'authorization missing'))
    }
    //02 key验证jwt:解签
    try {
        const userInfo = await decode(token)
        if (!userInfo) {
            return next(new HttpException(401, 'token 内容不存在', 'token content error'))
        }
        console.log("-----门卫放过-------");
        //03解签成功
        //token 方便后期controller
        req.user = userInfo
        req.token = token
        return next()
    } catch (error) {
        return next(new HttpException(401, 'authorization token验证失败', error.message))
    }

}
module.exports = authMiddleware